﻿Imports System.Xml.Linq
Imports System.Linq

Public Class Bridge

    Dim token As String = ""
    Dim usrName As String = ""
    Dim passW As String = ""
    Dim urlBase As String = "https://sureflix.fogbugz.com/api.asp?"


    Public Sub New(ByVal username As String, ByVal password As String, ByVal apiEndPoint As String)
        urlBase = apiEndPoint
        usrName = username
        passW = password
        logIn()
    End Sub

	Private Sub logIn()
        'https://sureflix.fogbugz.com/api.asp?cmd=logon&email=hernan@sureflix.com&password=112233
		If Not token.Length > 0 Then
            Dim xml = callApi("cmd=logon&email=" & usrName & "&password=" & passW)
			Try
				token = xml.<token>.First().Value
			Catch ex As Exception
				ex.Source = xml.ToString()
				Throw ex
			End Try

		End If

	End Sub

	Private Function callApi(ByVal params As String) As XElement
		If token.Length > 0 Then
			Return XElement.Load(urlBase & "token=" & token & "&" & params)
		End If

		Return XElement.Load(urlBase & params)

	End Function

	Public Sub SetFilter(ByVal filterId As String)

		callApi("cmd=saveFilter&sFilter=" & filterId)

	End Sub

	Public Function Search(ByVal options As String) As XElement
		Return callApi("cmd=search&" & options)
	End Function

	Public Function RunCommand(ByVal command As String) As XElement
		Return callApi("cmd=" & command)
	End Function
End Class

